<!-- ***************************************************************************
* Copyright (c) 2013 IBM Corp.
* Copyright 2017 Huawei Technologies Co., Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*    http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**************************************************************************** -->
<!-- this sourcecode is modified by Huawei Technologies Co., Ltd. -->
<!DOCTYPE HTML>
<html>

<head>
  <title>Huawei Air - flights</title>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
  <link rel="stylesheet" type="text/css" href="css/style.css">
  <link rel="stylesheet" href="css/themes/claro/claro.css">
  <link rel="stylesheet" href="css/themes/dijit.css">
  <link rel="stylesheet" href="css/themes/claro/claroGrid.css">
  
  <script type="text/javascript" src="js/acmeair-common.js"></script>
  <script src="https://download.dojotoolkit.org/release-1.7.12/dojo-release-1.7.12/dojo/dojo.js" djConfig="parseOnLoad: true"></script>

  <script>
	dojo.require("dojo.parser");
			
	dojo.require("dijit.Dialog");
	dojo.require("dijit.layout.StackContainer");
	dojo.require("dijit.layout.ContentPane");
	dojo.require("dijit.form.DateTextBox");
	dojo.require("dijit.form.FilteringSelect");
	dojo.require("dijit.form.CheckBox");
    dojo.require("dijit.Toolbar");
    dojo.require("dijit.Declaration");
	
	dojo.require("dojo.currency");
	
	dojo.require("dojo.store.Memory");
	dojo.require("dojox.grid.DataGrid");
	dojo.require("dojo.data.ItemFileReadStore");
	dojo.require("dojo.data.ItemFileWriteStore");
	
	function searchForFlights() {
		var fromAirport = dijit.byId('fromAirport').get('value');
		var toAirport = dijit.byId('toAirport').get('value');
		var fromDate = dijit.byId('fromDate').get('value');
		var returnDate = dijit.byId('toDate').get('value');
		var fromDateFormatted = dojo.date.stamp.toISOString(new Date(fromDate));
		var returnDateFormatted = dojo.date.stamp.toISOString(new Date(returnDate));
		var oneWayChecked = dijit.byId('oneWayCheck').checked;
		dojo.xhrPost({
			content : {
				fromAirport: fromAirport,
				toAirport: toAirport,
				fromDate: fromDateFormatted.toString(),
				returnDate: returnDateFormatted.toString(),
				oneWay: oneWayChecked
			},
			url: 'bookings/rest/api/flights/queryflights',
			handleAs: "json",
			load: function(response, ioArgs) {
				if (response.tripFlights.length == 0) {
					alert("no flights");
					return;
				}
				
				if (response.tripFlights.length > 2) {
					alert("returned more than 2 trip legs - not yet supported in this UI");
					return;
				}
				
				var stack = dijit.byId("stackContainer");
				stack.forward();
				
				var gridOutbound = dijit.byId("gridOutbound");
				var theDataTo = { items : response.tripFlights[0].flightsOptions };
				var newStoreTo = new dojo.data.ItemFileWriteStore({
					data : theDataTo
				});
				gridOutbound.setStore(newStoreTo);
				if (response.tripFlights[0].flightsOptions.length > 0) {
					// TODO: why is flightSegment and originPort an array???
					dojo.byId("outboundFrom").innerHTML = airportCodeToAirportName(response.tripFlights[0].flightsOptions[0].flightSegment[0].originPort[0]);
					dojo.byId("outboundTo").innerHTML = airportCodeToAirportName(response.tripFlights[0].flightsOptions[0].flightSegment[0].destPort[0]);
				}
				
				var gridReturn = dijit.byId("gridReturn");
				if (response.tripFlights.length == 2) {
					var theDataFrom = { items : response.tripFlights[1].flightsOptions };
					var newStoreFrom = new dojo.data.ItemFileWriteStore({
						data : theDataFrom
					});
					gridReturn.setStore(newStoreFrom);
					if (response.tripFlights[1].flightsOptions.length > 0) {
						// TODO: why is flightSegment and originPort an array???
						dojo.byId("returnFrom").innerHTML = airportCodeToAirportName(response.tripFlights[1].flightsOptions[0].flightSegment[0].originPort[0]);
						dojo.byId("returnTo").innerHTML = airportCodeToAirportName(response.tripFlights[1].flightsOptions[0].flightSegment[0].destPort[0]);
					}
				}
				else {
					// clear the store
					gridReturn.setStore(new dojo.data.ItemFileWriteStore({data: {items: []}})); 
				}
			},
			error: function(response, ioArgs) {
				alert(response);
			}
		});
	}
		
	
	function browseForFlights() {
		var fromAirport = dijit.byId('fromAirport').get('value');
		var toAirport = dijit.byId('toAirport').get('value');
		var oneWayChecked = dijit.byId('oneWayCheck').checked;
		dojo.xhrPost({
			content : {
				fromAirport: fromAirport,
				toAirport: toAirport,
				oneWay: oneWayChecked
			},
			url: 'bookings/rest/api/flights/browseflights',
			handleAs: "json",
			load: function(response, ioArgs) {
				if (response.tripFlights.length == 0) {
					alert("no flights");
					return;
				}
				
				if (response.tripFlights.length > 2) {
					alert("returned more than 2 trip legs - not yet supported in this UI");
					return;
				}
				
				var stack = dijit.byId("stackContainer");
				stack.forward();
				
				var gridOutbound = dijit.byId("gridOutbound");
				var theDataTo = { items : response.tripFlights[0].flightsOptions };
				var newStoreTo = new dojo.data.ItemFileWriteStore({
					data : theDataTo
				});
				gridOutbound.setStore(newStoreTo);
				if (response.tripFlights[0].flightsOptions.length > 0) {
					// TODO: why is flightSegment and originPort an array???
					dojo.byId("outboundFrom").innerHTML = airportCodeToAirportName(response.tripFlights[0].flightsOptions[0].flightSegment[0].originPort[0]);
					dojo.byId("outboundTo").innerHTML = airportCodeToAirportName(response.tripFlights[0].flightsOptions[0].flightSegment[0].destPort[0]);
				}
				
				var gridReturn = dijit.byId("gridReturn");
				if (response.tripFlights.length == 2) {
					var theDataFrom = { items : response.tripFlights[1].flightsOptions };
					var newStoreFrom = new dojo.data.ItemFileWriteStore({
						data : theDataFrom
					});
					gridReturn.setStore(newStoreFrom);
					if (response.tripFlights[1].flightsOptions.length > 0) {
						// TODO: why is flightSegment and originPort an array???
						dojo.byId("returnFrom").innerHTML = airportCodeToAirportName(response.tripFlights[1].flightsOptions[0].flightSegment[0].originPort[0]);
						dojo.byId("returnTo").innerHTML = airportCodeToAirportName(response.tripFlights[1].flightsOptions[0].flightSegment[0].destPort[0]);
					}
				}
				else {
					// clear the store
					gridReturn.setStore(new dojo.data.ItemFileWriteStore({data: {items: []}})); 
				}
			},
			error: function(response, ioArgs) {
				alert(response);
			}
		});
	}
	
	function changeReturnAtEnabled() {
		var state = dijit.byId('oneWayCheck').checked;
		if (state) {
			document.getElementById('toDateDiv').style.visibility = 'hidden'; 
		}
		else {
			document.getElementById('toDateDiv').style.visibility = 'visible'; 
		}
	}
			
	dojo.addOnLoad(pageLoaded);
			
	function pageLoaded() {
	   	updateLoggedInUserWelcome();
	}
		    
	function returnIfNotLoggedIn() {
		var loggedinuser = dojo.cookie("loggedinuser");
		if (loggedinuser == null) {
			alert("you need to login first before selecting flights");
			return true;
		}
		return false;
	}

	function cellclick(e) {
		if (returnIfNotLoggedIn()) { return }
		
		var gridId = e.grid.id;
		var selectedIndex = getCurrentlySelectedIndexForGrid(gridId);
		
		var grid = dijit.byId(gridId);
		
		if (grid.getItem(e.rowIndex).selected && grid.getItem(e.rowIndex).selected == "selected") {
			grid.getItem(e.rowIndex).selected = '...';
			if (e.rowIndex == selectedIndex) {
				selectedIndex = -1;
			}
		}
		else {
			grid.getItem(e.rowIndex).selected = 'selected';
			selectedIndex = e.rowIndex; 
		}
		
		setCurrentlySelectedIndexForGrid(gridId, selectedIndex);
		
		var store = grid.store;
		store.close();
		grid.setStore(store);
	}
	
	function getCurrentlySelectedIndexForGrid(gridId) {
		if (gridId == 'gridOutbound') {
			return selectedIndexForToFlights;
		}
		else if (gridId == 'gridReturn') {
			return selectedIndexForRetFlights;
		}
		else {
			console.error("wrong grid specified");
		}
	}
	
	function setCurrentlySelectedIndexForGrid(gridId, value) {
		if (gridId == 'gridOutbound') {
			selectedIndexForToFlights = value;
		}
		else if (gridId == 'gridReturn') {
			selectedIndexForRetFlights = value;
		}
		else {
			console.error("wrong grid specified");
		}
	}
	
	function bookFlights() {
		if (returnIfNotLoggedIn()) { return }

		var loggedinuser = dojo.cookie("loggedinuser");
		
		if (selectedIndexForToFlights == -1) {
			alert("please select an outbound flight");
			return;
		}
		var grid = dijit.byId("gridOutbound");
		var toFlightId = grid.store.getValue(grid.getItem(selectedIndexForToFlights), "_id");
		var toFlightSegId = grid.store.getValue(grid.getItem(selectedIndexForToFlights), "flightSegmentId");
		var toScheduledDepartureTime = grid.store.getValue(grid.getItem(selectedIndexForToFlights), "scheduledDepartureTime");
		var toScheduledArrivalTime = grid.store.getValue(grid.getItem(selectedIndexForToFlights), "scheduledArrivalTime");
		
		var retFlightId;
		var retFlightSegId;
		var oneWayFlight = dijit.byId('oneWayCheck').checked;
		if (!oneWayFlight) {
			if (selectedIndexForRetFlights == -1) {
				alert("please select an return flight");
				return;
			}
			var grid = dijit.byId("gridReturn");
			retFlightId = grid.store.getValue(grid.getItem(selectedIndexForRetFlights), "_id");			
			retFlightSegId = grid.store.getValue(grid.getItem(selectedIndexForRetFlights), "flightSegmentId");
			var retScheduledDepartureTime = grid.store.getValue(grid.getItem(selectedIndexForToFlights), "scheduledDepartureTime");
			var retScheduledArrivalTime = grid.store.getValue(grid.getItem(selectedIndexForToFlights), "scheduledArrivalTime");
		}
		
		var xhrContent = { userId : loggedinuser }
		xhrContent.toFlightId = toFlightId;
		xhrContent.toFlightSegId = toFlightSegId;
		xhrContent.fromAirPortName = dojo.byId("outboundFrom").innerHTML;
		xhrContent.toAirPortName = dojo.byId("outboundTo").innerHTML;
		xhrContent.toScheduledDepartureTime = toScheduledDepartureTime;
		xhrContent.toScheduledArrivalTime = toScheduledArrivalTime;
		//TODO: those 2 properties should change to read from table
		xhrContent.toFlightClass = 1;
		xhrContent.toFlightPrice = 200;

		if (!oneWayFlight) {
			xhrContent.retFlightId = retFlightId;
			xhrContent.retFlightSegId = retFlightSegId;
			xhrContent.retScheduledDepartureTime = retScheduledDepartureTime;
			xhrContent.retScheduledArrivalTime = retScheduledArrivalTime;

			//TODO: those 2 properties should change to read from table
			xhrContent.retFlightClass = 1;
			xhrContent.retFlightPrice = 200;
		}
		xhrContent.oneWayFlight = oneWayFlight;
		
		dojo.xhrPost({
			//url : 'bookings/rest/api/bookings/bookflights',
			url: 'orders/huaweiair/v1/orders',
			postData: dojo.toJson(xhrContent),
			headers: {'Content-Type': 'Application/json'},
			handleAs: "json",
			load : function(response, ioArgs) {
				alert("Book flights succeed.");
				window.location.href = "/orders.html";
			},
			error : function(response, ioArgs) {
				alert("Book flight failure.\n" + response);
			}
		});
	}
	
	function formatSelected(data) {
		// TODO:  not sure why setting the value results in only one character, but trying to make progress
		// I see the data value in alert either being "s" or ".", the first character of the entire string I set
		if (data && (data == "selected" || data == 's')) {
			return "selected";
		}
		else {
			return "select ...";
		}
	}
	
	var selectedIndexForToFlights = -1;
	var selectedIndexForRetFlights = -1;
	
		</script>
</head>

<body class="claro">
<span id="variousDialogs" style="display:none">
<div dojoType="dijit.Dialog" id="loginWaitDialog" title="Please Wait">
		<table width="258">
			<tr><td>Logging in ...</td></tr>
		</table>
</div>

<div dojoType="dijit.Dialog" id="loginDialog" title="Login">
		<table width="258">
			<tr>
				<td><label>Login</label></td>
				<td><input type="text" trim="true" dojoType="dijit.form.TextBox" value="uid0@email.com" name="login" id="userId"/></td>
			</tr>
			<tr>
				<td><label>Password</label></td>
				<td><input type="password" trim="true" dojoType="dijit.form.TextBox" value="password" name="password" id="password"/></td>
			</tr>
			<tr>
				<td colspan="2">&nbsp;</td>
			</tr>
			<tr>
				<td colspan="2" align="center">
					<table width="100%" border="0" cellspacing="0" cellpadding="0">
						<tr>
							<td  align="center" valign="top" width="40%"><button dojoType="dijit.form.Button" id="LoginButton" onClick="login()">Ok</button></td>
							<td align="left" valign="top" width="3%">&nbsp;</td>
							<td align="left" valign="top" width="57%"><button dojoType="dijit.form.Button" onclick="hideLoginDialog()" id="Cancel">Cancel</button></td>
						</tr>
					</table>
				</td>
			</tr>
		</table>
</div>
<div dojoType="dijit.Dialog" id="bookingStatusDialog" title="Booking Status">
	<p>Successfully booked flight(s)</p>
	To Flight:  <div id="bookingToFlight"></div><br/>
	Return Flight:  <div id="bookingReturnFlight"></div><br/>
	<button dojoType="dijit.form.Button" onclick="dijit.byId('bookingStatusDialog').hide()" id="bookingStatusDialogOkButton">Ok</button>
</div>
</span>
<div data-dojo-type="dojo.store.Memory"
    data-dojo-id="airportStore"
    data-dojo-props="data: airportCodes"></div>
    
<div id="main">
	<br/>
	<header>
		<br/><br/><br/>
		<img src="images/Huawei Air.png" alt="Huawei Air"/><br/><br/>
		<div class="text-align: left">Our commitment, your pursuit.</div><br/>
	</header>
	<div id="welcomeback"><div id="loggedinwelcome"></div>
	</div>
	<div id="main_content">
		<span data-dojo-type="dijit.Declaration" data-dojo-props='widgetClass:"ToolbarSectionStart", defaults:{ label: "Label"}'>
			<span data-dojo-type="dijit.ToolbarSeparator"></span><i>${label}:</i>
		</span>

		<div id="toolbar5" data-dojo-type="dijit.Toolbar">
			<div data-dojo-type="ToolbarSectionStart" data-dojo-props='label:"Actions"'></div>
			<div id="toolbar5.home" data-dojo-type="dijit.form.Button" data-dojo-props='showLabel:true' onClick="window.location='index.html'">Home</div>
			<div id="toolbar5.flights" data-dojo-type="dijit.form.Button" data-dojo-props='showLabel:true' onClick="window.location='flights.html'">Flights</div>
			<div id="toolbar5.order" data-dojo-type="dijit.form.Button" data-dojo-props='showLabel:true' onClick="window.location='orders.html'">Orders</div>
			<div id="toolbar5.login" data-dojo-type="dijit.form.Button" data-dojo-props='showLabel:true' onClick="showLoginDialog()">Login</div>
			<div id="toolbar5.logout" data-dojo-type="dijit.form.Button" data-dojo-props='showLabel:true' onClick="logout()">Logout</div>
			<div id="toolbar5.account" data-dojo-type="dijit.form.Button" data-dojo-props='showLabel:true' onClick="window.location='customerprofile.html'">Account</div>
		</div>
		
		<div class="content">
		<div data-dojo-type="dijit.layout.StackContainer" id="stackContainer" data-dojo-props="doLayout: false">
			<div data-dojo-type="dijit.layout.ContentPane" title="query">
<label for="oneWayCheck">One Way Flight: </label><input id="oneWayCheck" name="oneWayCheck" dojoType="dijit.form.CheckBox" value="oneway" onChange="changeReturnAtEnabled()"></input><br/>
<label for="fromAirport">Leave From: </label><select dojoType="dijit.form.FilteringSelect" value="" name="fromAirport" id="fromAirport" data-dojo-props="store:airportStore, searchAttr:'airportName'" required="true"></select><br/>
<label for="toAirport">Arrive &emsp;&ensp;At: </label><select dojoType="dijit.form.FilteringSelect" value="" name="toAirport" id="toAirport" data-dojo-props="store:airportStore, searchAttr:'airportName'" required="true"></select><br/>
<label for="fromDate">Leave &nbsp;On: </label><input type="text" name="fromDate" id="fromDate" data-dojo-type="dijit.form.DateTextBox" required="false" value="now"/><br/>
<div id="toDateDiv"><label for="toDate">Return On: </label><input type="text" name="toDate" id="toDate" data-dojo-type="dijit.form.DateTextBox" required="false" value="now"/><br/></div>
<button dojoType="dijit.form.Button" id="SearchByDepartureAirport" onClick="searchForFlights()">Find Flights</button><button dojoType="dijit.form.Button" id="BrowseByAirport" onClick="browseForFlights()">Browse Flights</button><br/>
			</div>
			<div data-dojo-type="dijit.layout.ContentPane" title="results" id="pane2">
				<h1>Outbound flights from <span id="outboundFrom"></span> to <span id="outboundTo"></span></h1>
				<table data-dojo-type="dojox.grid.DataGrid" id="gridOutbound" style="height: 200px">
					<script type="dojo/connect" event="onCellClick" args="e">cellclick(e)</script> 
    	        	<thead>
        	        	<tr>
							<th field="flightSegmentId" width="80px">Flight</th>
							<th field="scheduledDepartureTime" formatter="dateFormatter" width="175px">Departure Time</th>
							<th field="scheduledArrivalTime" formatter="dateFormatter" width="175px">Arrival Time</th>
							<th field="firstClassBaseCost" formatter="currencyFormatter" width="120px">First Class Cost</th>
							<th field="economyClassBaseCost" formatter="currencyFormatter" width="120px">Economy Cost</th>
							<th field="selected" width="120px" formatter="formatSelected">Select Flight</th>
						</tr>
					</thead>
				</table>
				<h1>Return flights from <span id="returnFrom"></span> to <span id="returnTo"></span></h1>
				<table data-dojo-type="dojox.grid.DataGrid" id="gridReturn" style="height: 200px">
					<script type="dojo/connect" event="onCellClick" args="e">cellclick(e)</script>
    	        	<thead>
        	        	<tr>
							<th field="flightSegmentId" width="80px">Flight</th>
							<th field="scheduledDepartureTime" formatter="dateFormatter" width="175px">Departure Time</th>
							<th field="scheduledArrivalTime" formatter="dateFormatter" width="175px">Arrival Time</th>
							<th field="firstClassBaseCost" formatter="currencyFormatter" width="120px">First Class Cost</th>
							<th field="economyClassBaseCost" formatter="currencyFormatter" width="120px">Economy Cost</th>
							<th field="selected" width="120px" formatter="formatSelected">Select Flight</th>
						</tr>
					</thead>
				</table>
				<button dojoType="dijit.form.Button" id="redoSearch" onClick="dijit.byId('stackContainer').back()">Redo Search</button>
				<button dojoType="dijit.form.Button" id="bookFlights" onClick="bookFlights()">Book Selected Flights</button>
			</div>
		</div>
		</div>
	</div>
	<footer>
		<p><a href="config.html">configure the Huawei Air environment.</a></p>
	</footer>
</div>

<p>&nbsp;</p>
</body>
</html>
